package br.com.canvasForAll.model.services;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Named;

import br.com.canvasForAll.model.entity.Canvas;
import br.com.canvasForAll.model.entity.Perfil;
import br.com.canvasForAll.model.repository.CanvasRepository;
import br.com.canvasForAll.model.repository.PerfilRepository;
import br.com.canvasForAll.model.services.interfaces.CanvasService;

@Stateless
@Named("canvasService")
public class CanvasServiceImpl implements CanvasService {

	@EJB private CanvasRepository canvasRepository;
	@EJB private PerfilRepository perfilRepository;

	@Override
	public Canvas salvarCanvas(Canvas c) throws Exception {
		if (c.getId() == null)
			canvasRepository.criar(c);
		else
			canvasRepository.atualizar(c);

		return c;
	}

	@Override
	public Canvas obterPorId(Long id) throws Exception {
		return canvasRepository.obterId(id);
	}

	@Override
	public Canvas adicionarParticipantes(Canvas c, List<Perfil> perfil)
			throws Exception {
		if (c != null && perfil != null && !perfil.isEmpty()) {
			c.setParticipantes(new ArrayList<Perfil>());
			for (Perfil p : perfil)
				c.getParticipantes().add(p);

			c = salvarCanvas(c);
		}
		return c;
	}

	@Override
	public Canvas obterPorIds(Long id, Long idMobile) throws Exception {
		return canvasRepository.obterPorIds(id, idMobile);
	}

	@Override
	public Collection<Canvas> obterCanvasResponsavel(Long idPerfil)
			throws Exception {
		Collection<Canvas> canvas = new ArrayList<>();
		if (idPerfil != null) {
			Perfil perfil = perfilRepository.obterId(idPerfil);
			canvas = canvasRepository.obterCanvasResponsavel(perfil);
		}

		return canvas;
	}

	@Override
	public Collection<Canvas> obterCanvasParticipante(Long idPerfil)
			throws Exception {
		Collection<Canvas> canvas = new ArrayList<>();
		if (idPerfil != null) {
			Perfil perfil = perfilRepository.obterId(idPerfil);
			canvas = canvasRepository.obterCanvasParticipante(perfil);
		}

		return canvas;
	}

}
